package com.jdjw.modules.busassetapply.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.google.common.collect.Lists;
import com.jdjw.common.ResponseResult;
import com.jdjw.modules.busassetapply.entity.BusAssetApply;
import com.jdjw.modules.busassetapply.entity.BusAssetApplyCommit;
import com.jdjw.modules.busassetapply.entity.BusAssetApplySave;
import com.jdjw.modules.busassetapply.entity.BusAssetApplyVo;
import com.jdjw.modules.busassetapply.service.BusAssetApplyService;
import com.jdjw.modules.busassetarchives.entity.BusAssetArchives;
import com.jdjw.modules.busassetarchives.service.BusAssetArchivesService;
import com.jdjw.modules.wfactivity.entity.WfActivity;
import com.jdjw.modules.wfactivity.service.WfActivityService;
import com.jdjw.modules.wftask.entity.WfTask;
import com.jdjw.modules.wftask.service.WfTaskService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import javax.xml.ws.Response;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

/**
 * <p>
 * 村级资产——资产资源处置申请 前端控制器
 * </p>
 *
 * @author fq
 * @since 2021-07-13
 */
@RestController
@RequestMapping("/busassetapply")
public class BusAssetApplyController {

    @Autowired
    private BusAssetApplyService busAssetApplyService;

    @Autowired
    private BusAssetArchivesService busAssetArchivesService;

    @Autowired
    protected WfActivityService wfActivityService;

    @Autowired
    private WfTaskService wfTaskService;

    @ApiOperation("资产资源处置-查询")
    @PostMapping("queryAll")
    public ResponseResult queryAll(BusAssetApplyVo busAssetApplyVo){
        return busAssetApplyService.queryAll(busAssetApplyVo);
    }


    @ApiOperation("资产资源处置-添加")
    @PostMapping("save")
    public ResponseResult save(BusAssetApplySave busAssetApplysave){
        ResponseResult r=new ResponseResult();
        try {
            BusAssetApply busAssetApply=new BusAssetApply();
            //转换
            BeanUtils.copyProperties(busAssetApplysave,busAssetApply);
            SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            busAssetApply.setCreateDate(s.format(new Date()));
            busAssetApply.setStatus("0");//状态
            busAssetApply.setPassFlag("0");//投标单位
            busAssetApplyService.save(busAssetApply);
            wfActivityService.createWorkFlow("CJZCZYLC", busAssetApply.getDeptId(),busAssetApply.getId(),busAssetApply.getCreateBy(),busAssetApply.getUsername());
            r.setCode(200);
            r.setMsg("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("保存失败"+e.getMessage());
        }
        return r;
    }



    @ApiOperation("资产资源处置-编辑")
    @PostMapping("edit")
    public ResponseResult query(@RequestBody String sqlEdit) throws JSONException {
        JSONObject json=new JSONObject(sqlEdit);
        return busAssetApplyService.edit(json.getString("sqlEdit"));
    }


    @ApiOperation("资产资源处置-删除")
    @PostMapping("delete")
    public ResponseResult delete(String[] ids){
        ResponseResult responseResult=new ResponseResult();
        System.out.println(ids);
        List<String> strings = Arrays.asList(ids);
        boolean b = busAssetApplyService.removeByIds(strings);
        if(b){
            responseResult.setCode(200);
            responseResult.setMsg("删除成功");
        }else{
            responseResult.setCode(500);
            responseResult.setMsg("删除失败");
        }
        return responseResult;
    }

    @ApiOperation("资产资源处置-查看")
    @PostMapping("{id}/preview")
    @ResponseBody
    public Map<String,Object> preview(@PathVariable("id") String id){
        Map<String,Object> map=new HashMap<>();
        //查看单个信息
        BusAssetApply busAssetApply = busAssetApplyService.getById(id);
        Map<String,Object> mapone=new HashMap<>();
        mapone.put("apply_id", busAssetApply.getId());

        List<WfActivity> activityList = (List<WfActivity>) wfActivityService.listByMap(mapone);
        List<WfTask> taskList = Lists.newArrayList();
        if (activityList != null && activityList.size() > 0) {
            taskList = wfTaskService.queryByactivityId(activityList.get(0).getId());
            busAssetApply.setTaskList(taskList);
        }

        //部门信息
        String assetArchivesIds = "";
        String archivesNames = "";
        if(StringUtils.isNotBlank(busAssetApply.getAssetArchivesId())){
            assetArchivesIds =busAssetApply.getAssetArchivesId();
            BusAssetArchives busAssetArchives = busAssetArchivesService.getById(busAssetApply.getAssetArchivesId());
            if(busAssetArchives!=null){
                archivesNames = busAssetArchives.getName();
            }
        }
        String priceFlag = "02"; // 01 50000 包括以内 50000 包括以外
        String price = busAssetApply.getPrice();
        if (StringUtils.isNotBlank(price)) {
            price = price.replaceAll("元", "");
            try {
                int priceInt = Integer.parseInt(price);
                if (priceInt <= 50000) {
                    priceFlag = "01";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String nodeCode = wfActivityService.findNodeCode(busAssetApply.getId());

        map.put("priceFlag", priceFlag);
        map.put("nodeCode", nodeCode);//节点标识
        map.put("assetArchivesIds", assetArchivesIds);
        map.put("archivesNames", archivesNames);
        map.put("data",busAssetApply);

        return map;
    }


    @ApiOperation("资产资源处置-提交")
    @PostMapping("commit")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult commit(@RequestBody BusAssetApplyCommit busAssetApplyCommit){

        BusAssetApply busAssetApply=busAssetApplyService.getById(busAssetApplyCommit.getId());

        String deptId2 = busAssetApplyCommit.getDeptId();
        String nextNodeCode = "";
        String nodeCode = wfActivityService.findNodeCode(busAssetApply.getId());
        if ("CSJSP".equals(nodeCode)) {
            String price = busAssetApply.getPrice();
            if (StringUtils.isNotBlank(price)) {
                price = price.replaceAll("元", "");
                try {
                    int priceInt = Integer.parseInt(price);
                    if (priceInt <= 50000) {
                        nextNodeCode = "QDHT";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        // 公开招标、签订合同数据保存
        if ("GKZB".equals(nodeCode) || "QDHT".equals(nodeCode)) {
            busAssetApplyService.updateById(busAssetApply);
            if("QDHT".equals(nodeCode)) { //签订合同 资产状态 回写到资源档案 资产状态
                BusAssetApply apply = busAssetApplyService.getById(busAssetApply.getId());
                Map<String, Object> map = new HashMap<>();
                map.put("id", apply.getAssetArchivesId());//处置id
                String tyep=apply.getType();//获取处置方式
                String status="";
                if(tyep.equals("1")) {//出租
                    status="0";
                }else if(tyep.equals("2")) {//流转
                    status="2";
                }else if(tyep.equals("3")) {//出借
                    status="4";
                }else if(tyep.equals("4")) {//报废
                    status="8";
                }else if(tyep.equals("5")) {//出售
                    status="9";
                }else if(tyep.equals("6")) {// 拍卖
                    status="10";
                }else if(tyep.equals("7")) {//兼并
                    status="11";
                }else if(tyep.equals("8")) {//拆除
                    status="12";
                }else if(tyep.equals("9")) {//投资入股
                    status="13";
                }else {//其他
                    status="6";
                }
                map.put("status", status);
                busAssetArchivesService.updatestatus(map);//更新资产资源档案
            }
        }
        ResponseResult responseResult=new ResponseResult();
        try {

            responseResult.setCode(200);
            responseResult.setMsg("提交成功");
            WfTask wfTask = busAssetApplyCommit.getWfTask();
            if (wfTask == null) {
                wfTask = new WfTask();
            }
            wfTask.setAttIds(busAssetApplyCommit.getWfTask().getAttIds());

            String dualOpinion = StringUtils.isBlank(wfTask.getDualOpinion()) ? "01" : wfTask.getDualOpinion();
            BusAssetApply busAssetApply1 = busAssetApplyService.getById(busAssetApply.getId());
            if ("01".equals(dualOpinion)) {  // 同意
                // 判断是否是特殊节点
                String[] userIdS = new String[]{busAssetApply1.getCreateBy()};
                if ("CSJSP".equals(nodeCode) && "QDHT".equals(nextNodeCode)) { // 村书记审批 小于等于5w 直接签订合同
                    //wfActivityService.sendAppointNoteDesingnatedPerson(busAssetApply.getId(), userIdS, nextNodeCode, wfTask);
                    //2021-06-23,需求变更不管金额大小都要走招投标流程
                    wfActivityService.sendNextNodeAllPerson(busAssetApplyCommit.getId(),busAssetApplyCommit.getUserId(),busAssetApplyCommit.getUsername(), deptId2, wfTask);
                } else if ("GKZB".equals(nodeCode) || "CSJSP".equals(nodeCode)) { // 村民代表会议决议 村书记审批 同意提交后 到经办人
                    wfActivityService.sendNextNoteDesingnatedPerson(busAssetApplyCommit.getId(),busAssetApplyCommit.getUserId(),busAssetApplyCommit.getUsername(), userIdS, wfTask);
                } else if("QDHT".equals(nodeCode)){
                    busAssetApply1.setPassFlag("2");
                    busAssetApplyService.updateById(busAssetApply1);
                    wfActivityService.sendNextNodeAllPerson(busAssetApplyCommit.getId(),busAssetApplyCommit.getUserId(),busAssetApplyCommit.getUsername(), deptId2, wfTask);
                } else {
                    wfActivityService.sendNextNodeAllPerson(busAssetApplyCommit.getId(),busAssetApplyCommit.getUserId(),busAssetApplyCommit.getUsername(), deptId2, wfTask);
                }
            } else if ("02".equals(dualOpinion)) { // 不同意
                busAssetApply1.setPassFlag("1");
                busAssetApplyService.updateById(busAssetApply1);
                wfActivityService.sendAppointNodeAllPerson(busAssetApplyCommit.getId(),busAssetApplyCommit.getUserId(),busAssetApplyCommit.getUsername(), deptId2, "GD", wfTask);
            } else if ("04".equals(dualOpinion)) { // 退回
                wfActivityService.sendBack(busAssetApplyCommit.getId(),busAssetApplyCommit.getUserId(),busAssetApplyCommit.getUsername(), deptId2, wfTask);
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseResult.setCode(500);
            responseResult.setMsg("提交失败");
        }

        return responseResult;
    }

}

